package com.htzy.extrace.encrypt;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
 * AES加密解密
 * @author chenwenyan
 *
 */
public class encriptTest1 {
	public static byte[] iv = {1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8};  
	//化向量参数，AES 为16bytes. DES 为8bytes.  
	public  String encode(String source) {  
	    try {  
	          
	        IvParameterSpec zeroIv = new IvParameterSpec(iv);  
	        SecretKeySpec key1 = new SecretKeySpec(iv, "AES");  
	        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");  
	        cipher.init(Cipher.ENCRYPT_MODE, key1, zeroIv);  
	        byte[] encryptedData = cipher.doFinal(source.getBytes());  
	      String encryptResultStr = parseByte2HexStr(encryptedData);  
	      return encryptResultStr; // 加密  
	  } catch (Exception e) {  
	      e.printStackTrace();  
	      return "";  
	  }  
	}	  
	  



	public  String decode(String content) {  
	    try {  
	        byte[] decryptFrom = parseHexStr2Byte(content);  
	          
	        IvParameterSpec zeroIv = new IvParameterSpec(iv);  
	        SecretKeySpec key1 = new SecretKeySpec(iv, "AES");  
	        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");  
	        cipher.init(Cipher.DECRYPT_MODE, key1, zeroIv);  
	        byte decryptedData[] = cipher.doFinal(decryptFrom);  
	        return new String(decryptedData); // 加密  
	    } catch (Exception e) {  
	        e.printStackTrace();  
	        return "";  
	    }  
	} 
	
	/**将二进制转换成16进制
	 * @param buf
	 * @return
	 */ 
	public static String parseByte2HexStr(byte buf[]) { 
	        StringBuffer sb = new StringBuffer(); 
	        for (int i = 0; i < buf.length; i++) { 
	                String hex = Integer.toHexString(buf[i] & 0xFF); 
	                if (hex.length() == 1) { 
	                        hex = '0' + hex; 
	                } 
	                sb.append(hex.toUpperCase()); 
	        } 
	        return sb.toString(); 
	} 
	
	/**将16进制转换为二进制
	 * @param hexStr
	 * @return
	 */ 
	public static byte[] parseHexStr2Byte(String hexStr) { 
	        if (hexStr.length() < 1) 
	                return null; 
	        byte[] result = new byte[hexStr.length()/2]; 
	        for (int i = 0;i< hexStr.length()/2; i++) { 
	                int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16); 
	                int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16); 
	                result[i] = (byte) (high * 16 + low); 
	        } 
	        return result; 
	} 

}
